<?php

require_once realpath (dirname (__FILE__) . '//..//..//pages.php');
require_once CLASS_FULL_TAG;
require_once CLASS_OPTION;

/**
 * Description of Select
 *
 * @author Andrea
 */
class Select extends FullTag {

    protected $auto_resize = true;

    /**
     * Creates a new select.
     * 
     * @param array $attributes containing the attributes that will be applied to this tag.
     * The array must contain as keys the name of the attributes, pointing to their values.
     * @param array|Option $options [Optional] containing Option objects or strings.
     * The array, if used with strings must contain as keys the name of the attributes, pointing to their values.|
     * Option object that will be added to this select.
     */
    public function __construct ($attributes = null, $options = null) {
        parent::__construct ('select', $attributes);
        if (is_a ($options, 'Option')) {
            $this->innerHTML[$this->index] = $options;
            $this->index++;
        } else if (is_array ($options)) {
            foreach ($options as $label => $value) {
                if (is_a ($value, 'Option')) {
                    $this->innerHTML[$this->index] = $value;
                } else if (is_string ($value)) {
                    $this->innerHTML[$this->index] = new Option ($label, $value);
                } else {
                    break;
                }
                $this->index++;
            }
        }
    }

    public function setSelected ($values) {
        foreach ($this->innerHTML as $option) {
            if (is_a ($option, 'Option')) {
                if (is_array ($values)) {
                    foreach ($values as $value) {
                        if ($option->getAttribute ('value') == $value) {
                            $option->addAttribute ('selected', 'selected');
                            break;
                        }
                    }
                } else if ($option->getAttribute ('value') == $values) {
                    $option->addAttribute ('selected', 'selected');
                    break;
                }
            }
        }
    }

    public function setAutoResize ($boolean) {
        $this->auto_resize = $boolean ? true : false;
    }

    public function __toString () {
        if ($this->auto_resize) {
            $size = 0;
            foreach ($this->innerHTML as $html) {
                if (is_a ($html, 'Option')) {
                    $size++;
                }
            }
            if ($size >= 4 && $size < 8) {
                $this->attributes['size'] = $size;
            }
        }
        return parent::__toString ();
    }

}

?>
